﻿using System;
using System.Collections;
using System.Collections.Generic;
using LitJson;
using SCore.Util;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
#if UNITY_EDITOR
using UnityEditor.AddressableAssets;
#endif

namespace Function.HotUpdate
{
    public class HotManager : ComMonoSingleton<HotManager>, IComponent
    {
        public Action<Version, Version> _remoteVersionGet; //检测到 远程资源版号
        public Action _needUpdate; //需要更新回调
        public Action<long> _resourceSize; //检测下载大小回调
        public Action<float> _downloadPercent; //下载进度回调
        public Action _disconnectNet; // 断网回调
        public Action _reconnectNet; //重连回调
        public Action _finishUpdate; //完成更新
        public Action<int> _errorPop; //错误弹窗;
        public HotContext _content;

        public delegate void CommonTraceC(string eventName, Dictionary<string, JsonData> paramsDic);

        public CommonTraceC _commonTrace;

        public void SetAddressableURL(string channel, string version, string addressableURL, string injectEnv)
        {
            _content._channel = channel;
            _content._addressableURL = addressableURL;
            if (version == string.Empty)
            {
                throw new Exception("version not can null");
            }

            _content._version = new Version(version);
            _content._bootVersion = new Version(version);
            _content._injectEnv = injectEnv;

            UnityEngine.Debug.Log($"[hotupdate] set content  {_content}");
        }

        public override void Init()
        {
            _content = new HotContext();
            base.Init();
        }

        private void Update()
        {
            _content?.Update();
        }

        public bool CanUpdate()
        {
            bool hotUpdate = false;
#if UNITY_EDITOR
            var settings = AddressableAssetSettingsDefaultObject.Settings;
            hotUpdate = settings.ActivePlayModeDataBuilder.Name == "Use Existing Build (requires built groups)";
#else
            hotUpdate = true;
#endif
            return hotUpdate;
        }

        public void StartUpdate()
        {
            if (CanUpdate())
            {
                var hotNode = new HotLightHouse(_content, false);
                hotNode
                    .Next(new HotCheckNeedUpdate(_content, false))
                    .Next(new HotInternalId(_content, false))
                    .Next(new HotAddressable(_content, false))
                    .Next(new HotDownload(_content, false))
                    .Next(new HotSaveVersion(_content, false));
                StartCoroutine(hotNode.Execute());
            }
            else
            {
                _finishUpdate?.Invoke();
            }
        }

        public static IEnumerator InitAddressableWithTimeout(float timeoutSeconds, Action<bool> callback)
        {
            // 初始化Addressables并获取异步操作句柄
            AsyncOperationHandle initHandle = Addressables.InitializeAsync(false);

            // 检查是否完成并记录开始时间
            float startTime = Time.time;
            while (!initHandle.IsDone)
            {
                if (Time.time - startTime > timeoutSeconds)
                {
                    // 处理超时逻辑
                    UnityEngine.Debug.LogError("[hotupdate] Addressables initialization timed out!");
                    callback?.Invoke(false);

                    // 释放句柄
                    Addressables.Release(initHandle);
                    yield break; // 退出协程
                }

                // 等待下一帧继续检查
                yield return null;
            }

            if (initHandle.Status == AsyncOperationStatus.Succeeded)
            {
                // 初始化成功
                UnityEngine.Debug.Log("[hotupdate] Addressables initialized successfully.");
                callback?.Invoke(true);
            }
            else
            {
                // 初始化失败，处理错误
                UnityEngine.Debug.LogError(
                    $"[hotupdate] Addressables initialization failed: {initHandle.OperationException?.Message}");
                callback?.Invoke(false);
            }

            // 释放句柄
            Addressables.Release(initHandle);
        }
    }
}